package com.xinbochuang.machine.admin.service.impl.plan;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinbochuang.machine.admin.domain.plan.*;
import com.xinbochuang.machine.admin.domain.vo.EquCabinetVo;
import com.xinbochuang.machine.admin.domain.vo.EquipmentVo;
import com.xinbochuang.machine.admin.domain.vo.MacRoomVo;
import com.xinbochuang.machine.admin.dto.PlanListDto;
import com.xinbochuang.machine.admin.mapper.plan.*;
import com.xinbochuang.machine.admin.service.plan.ICheckPlanService;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄晓鹏
 * @date 2020-09-10
 */
@Service
@Slf4j
public class CheckPlanServiceImpl extends ServiceImpl<CheckPlanMapper, CheckPlan> implements ICheckPlanService {

    @Resource
    private CheckPlanRoomMapper planRomeMapper;

    @Resource
    private MacRoomVoMapper roomVoMapper;

    @Resource
    private CheckRoomCabinetMapper romeCabinetMapper;

    @Resource
    private EquCabinetVoMapper cabinetVoMapper;

    @Resource
    private CheckCabinetEquMapper checkCabinetEquMapper;

    @Resource
    private EquipmentVoMapper equipmentVoMapper;

    @Resource
    private CheckPlanMapper checkPlanMapper;

    /**
     * 获取计划列表(废弃)
     *
     * @param checkPlan 计划对象
     * @return 计划集合
     */
    @Override
    public TableDataInfo selectPlanList(CheckPlan checkPlan) {
        //根据查询条件查询集合列表
        QueryWrapper<CheckPlan> queryWrapper = new QueryWrapper<>();
        if (checkPlan != null) {
            //计划名称
            if (StrUtil.isNotBlank(checkPlan.getUuid())) {
                queryWrapper.lambda().like(CheckPlan::getUuid, checkPlan.getUuid());
            }
            //计划名称
            if (StrUtil.isNotBlank(checkPlan.getCheckName())) {
                queryWrapper.lambda().like(CheckPlan::getCheckName, checkPlan.getCheckName());
            }
            //核查时间
            if (StrUtil.isNotBlank(checkPlan.getBeginTime()) && StrUtil.isNotBlank(checkPlan.getEndTime())) {
                queryWrapper.lambda().between(CheckPlan::getCheckTime, checkPlan.getBeginTime(), checkPlan.getEndTime());
            }
            if (StringUtils.isNotBlank(checkPlan.getRealUserId())) {
                queryWrapper.lambda().eq(CheckPlan::getRealUserId, checkPlan.getRealUserId());
            }
        }
        List<CheckPlan> planList;
        IPage<CheckPlan> list = new Page<>();
        if (checkPlan.getPageNum() == null) {
            planList = list(queryWrapper);
            list.setRecords(planList);
            list.setTotal(planList.size());
        } else {
            list = page(new Page<>(checkPlan.getPageNum(), checkPlan.getPageSize()), queryWrapper);
            planList = list.getRecords();
        }
        /**
         * 根据计划/机房对应，查询机房列表，放入计划中
         */
        for (CheckPlan plan : planList) {
            //计划/机房关联集合
            List<CheckPlanRoom> planRomeList = planRomeMapper.selectList(new QueryWrapper<CheckPlanRoom>().eq("PLAN_ID", plan.getUuid()));
            //机房ids
            List<String> romeIds = new ArrayList<>();
            for (CheckPlanRoom planRome : planRomeList) {
                romeIds.add(planRome.getRoomId());
            }
            if (!romeIds.isEmpty()) {
                //机房集合
                List<MacRoomVo> roomList = roomVoMapper.selectList(new QueryWrapper<MacRoomVo>().in("uuid", romeIds).eq("DELETE_FLAG", 0));
                //添加children
                plan.setChildren(roomList);
                /**
                 * 根据机房列表，查询机柜,放入机房中
                 */
                for (MacRoomVo macRoomVo : roomList) {
                    //planId
                    macRoomVo.setPlanId(plan.getUuid());
                    //机房/机柜关联集合
                    List<CheckRoomCabinet> romeCabinetList = romeCabinetMapper.selectList(new QueryWrapper<CheckRoomCabinet>().eq("PLAN_ID", plan.getUuid()).eq("ROOM_ID", macRoomVo.getUuid()));
                    //机柜ids
                    List<String> cabinetIds = new ArrayList<>();
                    for (CheckRoomCabinet checkRoomCabinet : romeCabinetList) {
                        cabinetIds.add(checkRoomCabinet.getCabinetId());
                    }
                    if (!cabinetIds.isEmpty()) {
                        //机柜集合
                        List<EquCabinetVo> cabinetVoList = cabinetVoMapper.selectList(new QueryWrapper<EquCabinetVo>().in("uuid", cabinetIds).eq("DELETE_FLAG", 0));
                        //添加children
                        macRoomVo.setChildren(cabinetVoList);
                        /**
                         *根据机柜列表，查询设备，放入机柜中
                         */
                        for (int i = 0; i < cabinetVoList.size(); i++) {
                            //planId
                            cabinetVoList.get(i).setPlanId(plan.getUuid());
                            //roomId
                            cabinetVoList.get(i).setRoomId(macRoomVo.getUuid());
                            EquCabinetVo equCabinetVo = cabinetVoList.get(i);
                            //机柜状态
                            equCabinetVo.setStatus(romeCabinetList.get(i).getStatus());
                            //机柜/设备关联集合
                            List<CheckCabinetEqu> checkCabinetEquList = checkCabinetEquMapper.selectList(new QueryWrapper<CheckCabinetEqu>().eq("PLAN_ID", plan.getUuid()).eq("CABINET_ID", equCabinetVo.getUuid()));
                            //机柜ids
                            List<String> equIds = new ArrayList<>();
                            for (CheckCabinetEqu cabinetEqu : checkCabinetEquList) {
                                equIds.add(cabinetEqu.getEquId());
                            }
                            if (!equIds.isEmpty()) {
                                //设备集合
                                List<EquipmentVo> equipmentVoList = equipmentVoMapper.selectList(new QueryWrapper<EquipmentVo>().in("uuid", equIds).eq("DELETE_FLAG", 0));
                                //添加children
                                equCabinetVo.setChildren(equipmentVoList);
                            }
                        }
                    }
                }
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.HTTP_OK);
        rspData.setMsg("查询成功");
        rspData.setRows(list.getRecords());
        rspData.setTotal(list.getTotal());
        return rspData;
    }

    /**
     * 获取计划列表
     *
     * @param checkPlan
     * @return 杜文博
     */
    @Override
    public List<PlanListDto> selectPlanRoomList(CheckPlan checkPlan) {

        String pageSize = checkPlan.getPageSize().toString();
        String pageNum = checkPlan.getPageNum().toString();
        String planId = checkPlan.getUuid();
        String planName = checkPlan.getCheckName();
        List<PlanListDto> list = checkPlanMapper.selectPlanList(planName, planId, pageNum, pageSize);
//        List<PlanListDto> result = new ArrayList<>();
//        PlanListDto planListDto = new PlanListDto();

//        if(list.size()>0){
//            for (int i=0;i<list.size();i++){
//                planListDto = checkPlanMapper.selectCheckPercentage(list.get(i).getPlanId());
//                if (planListDto!=null){
//                    list.get(i).setCheckPercentage(planListDto.getCheckPercentage());
//                }
//                result.add(list.get(i));
//            }
//        }
        return list;
    }

    @Override
    public List<PlanListDto> planMacRoomList(CheckPlan checkPlan) {
        String pageSize = checkPlan.getPageSize().toString();
        String pageNum = checkPlan.getPageNum().toString();
        String planId = checkPlan.getUuid();
        String planName = checkPlan.getCheckName();
        List<PlanListDto> list = checkPlanMapper.selectPlanList(planName, planId, pageNum, pageSize);
        return list;
    }

    @Override
    public Integer planMacRoomCount(CheckPlan checkPlan) {
        String pageSize = checkPlan.getPageSize().toString();
        String pageNum = checkPlan.getPageNum().toString();
        String planId = checkPlan.getUuid();
        String planName = checkPlan.getCheckName();
        return checkPlanMapper.planTotalCount(planName, planId, pageNum, pageSize);
    }

    /**
     * 获取机房核查计划分页列表
     *
     * @param checkPlan
     * @return
     */
    @Override
    public Integer selectTotalCount(CheckPlan checkPlan) {
        String pageSize = checkPlan.getPageSize().toString();
        String pageNum = checkPlan.getPageNum().toString();
        String planId = checkPlan.getUuid();
        String planName = checkPlan.getCheckName();
        return checkPlanMapper.planTotalCount(planName, planId, pageNum, pageSize);
    }

    /**
     * 添加核查计划
     *
     * @param checkPlan 核查计划对象
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPlan(CheckPlan checkPlan) {
        //插入计划
        save(checkPlan);
        if (checkPlan.getIds() != null && !checkPlan.getIds().isEmpty()) {
            //插入关系表
            addRelations(checkPlan);
        }
        return true;
    }

    /**
     * 修改核查计划
     *
     * @param checkPlan 计划对象
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePlan(CheckPlan checkPlan) {
        //修改计划
        updateById(checkPlan);
        if (checkPlan.getIds() != null && !checkPlan.getIds().isEmpty()) {
            //先删除关系表
            deleteRelations(checkPlan.getUuid());
            //插入关系表
            addRelations(checkPlan);
        }
        return true;
    }

    /**
     * 删除核查计划
     *
     * @param uuid 计划id
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePlan(String uuid) {
        //删除计划数据
        removeById(uuid);
        deleteRelations(uuid);
        return true;
    }

    @Override
    public TableDataInfo selectPlanListByApp(CheckPlan checkPlan) {
        //根据查询条件查询集合列表
        QueryWrapper<CheckPlan> queryWrapper = new QueryWrapper<>();
        if (checkPlan != null) {
            //计划名称
            if (StrUtil.isNotBlank(checkPlan.getCheckName())) {
                queryWrapper.lambda().like(CheckPlan::getCheckName, checkPlan.getCheckName());
            }
            //核查时间
            if (StrUtil.isNotBlank(checkPlan.getBeginTime()) && StrUtil.isNotBlank(checkPlan.getEndTime())) {
                queryWrapper.lambda().between(CheckPlan::getCheckTime, checkPlan.getBeginTime(), checkPlan.getEndTime());
            }
            if (StringUtils.isNotBlank(checkPlan.getRealUserId())) {
                queryWrapper.lambda().eq(CheckPlan::getRealUserId, checkPlan.getRealUserId());
            }
        }
        queryWrapper.lambda().orderByAsc(CheckPlan::getStatus);
        List<CheckPlan> planList;
        IPage<CheckPlan> list = new Page<>();
        if (checkPlan.getPageNum() == null) {
            planList = list(queryWrapper);
            list.setRecords(planList);
            list.setTotal(planList.size());
        } else {
            list = page(new Page<>(checkPlan.getPageNum(), checkPlan.getPageSize()), queryWrapper);
            planList = list.getRecords();
        }
        /**
         * 根据计划/机房对应，查询机房列表，放入计划中
         */
        for (CheckPlan plan : planList) {
            //计划/机房关联集合
            List<CheckPlanRoom> planRomeList = planRomeMapper.selectList(new QueryWrapper<CheckPlanRoom>().eq("PLAN_ID", plan.getUuid()));
            //机房ids
            List<String> romeIds = new ArrayList<>();
            for (CheckPlanRoom planRome : planRomeList) {
                romeIds.add(planRome.getRoomId());
            }
            if (!romeIds.isEmpty()) {
                //机房集合
                List<MacRoomVo> roomList = roomVoMapper.selectList(new QueryWrapper<MacRoomVo>().in("uuid", romeIds));
                //添加children
                plan.setChildren(roomList);
                /**
                 * 根据机房列表，查询机柜,放入机房中
                 */
                for (MacRoomVo macRoomVo : roomList) {
                    //planId
                    macRoomVo.setPlanId(plan.getUuid());
                    //机房/机柜关联集合
                    List<CheckRoomCabinet> romeCabinetList = romeCabinetMapper.selectList(new QueryWrapper<CheckRoomCabinet>().eq("PLAN_ID", plan.getUuid()).eq("ROOM_ID", macRoomVo.getUuid()));
                    //机柜ids
                    List<String> cabinetIds = new ArrayList<>();
                    for (CheckRoomCabinet checkRoomCabinet : romeCabinetList) {
                        cabinetIds.add(checkRoomCabinet.getCabinetId());
                    }
                    if (!cabinetIds.isEmpty()) {
                        //机柜集合
                        List<EquCabinetVo> cabinetVoList = cabinetVoMapper.selectList(new QueryWrapper<EquCabinetVo>().in("uuid", cabinetIds));
                        //添加children
                        macRoomVo.setChildren(cabinetVoList);
                        /**
                         *根据机柜列表，查询设备，放入机柜中
                         */
                    }
                }
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.HTTP_OK);
        rspData.setMsg("查询成功");
        rspData.setRows(list.getRecords());
        rspData.setTotal(list.getTotal());
        return rspData;
    }

    /**
     * 盘点总进度
     *
     * @return 结果
     */
    @Override
    public Double selectPlanCount() {
        return checkPlanMapper.selectPlanCount();
    }


    /**
     * 插入计划关系表
     *
     * @param checkPlan 计划对象
     * @return 是否成功
     */
    private boolean addRelations(CheckPlan checkPlan) {
        List<CheckRes> resList = checkPlan.getIds();
        for (CheckRes checkRes : resList) {
            //插入计划/机房关系表
            if (planRomeMapper.selectOne(new QueryWrapper<CheckPlanRoom>().eq("PLAN_ID", checkPlan.getUuid()).eq("ROOM_ID", checkRes.getRoomId())) == null) {
                CheckPlanRoom planRoom = new CheckPlanRoom();
                planRoom.setPlanId(checkPlan.getUuid());
                planRoom.setRoomId(checkRes.getRoomId());
                planRomeMapper.insert(planRoom);
            }
            //插入机房/机柜关系表
            if (romeCabinetMapper.selectOne(new QueryWrapper<CheckRoomCabinet>().eq("PLAN_ID", checkPlan.getUuid()).eq("ROOM_ID", checkRes.getRoomId()).eq("CABINET_ID", checkRes.getCabinetId())) == null) {
                CheckRoomCabinet roomCabinet = new CheckRoomCabinet();
                roomCabinet.setPlanId(checkPlan.getUuid());
                roomCabinet.setRoomId(checkRes.getRoomId());
                roomCabinet.setCabinetId(checkRes.getCabinetId());
                romeCabinetMapper.insert(roomCabinet);
            }
            //插入机柜/设备关系表
            if (checkCabinetEquMapper.selectOne(new QueryWrapper<CheckCabinetEqu>().eq("PLAN_ID", checkPlan.getUuid()).eq("EQU_ID", checkRes.getRoomId()).eq("CABINET_ID", checkRes.getCabinetId())) == null) {
                CheckCabinetEqu checkCabinetEqu = new CheckCabinetEqu();
                checkCabinetEqu.setPlanId(checkPlan.getUuid());
                checkCabinetEqu.setCabinetId(checkRes.getCabinetId());
                checkCabinetEqu.setEquId(checkRes.getEquId());
                checkCabinetEquMapper.insert(checkCabinetEqu);
            }
        }
        return true;
    }

    /**
     * 根据计划id，删除关联表
     *
     * @param planId 计划id
     * @return 是否成功
     */
    private boolean deleteRelations(String planId) {
        //删除计划/机房关系
        planRomeMapper.delete(new QueryWrapper<CheckPlanRoom>().eq("PLAN_ID", planId));
        //删除机房/机柜关系
        romeCabinetMapper.delete(new QueryWrapper<CheckRoomCabinet>().eq("PLAN_ID", planId));
        planRomeMapper.delete(new QueryWrapper<CheckPlanRoom>().eq("PLAN_ID", planId));
        //删除机柜/设备关系
        checkCabinetEquMapper.delete(new QueryWrapper<CheckCabinetEqu>().eq("PLAN_ID", planId));
        return true;
    }
}
